package com.example.blew.omp.system.util;

import cn.hutool.core.util.StrUtil;
import com.example.blew.omp.system.config.AppHttpCodeEnum;
import com.example.blew.omp.system.model.po.User;
import com.example.blew.omp.system.service.UserService;
import org.junit.jupiter.params.shadow.com.univocity.parsers.common.DataProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("token");

//        log.info("===============request start===============");
//        log.info("request uri:{}", request.getRequestURI());
//        log.info("request method:{}", request.getMethod());
//        log.info("token:{}", token);
//        log.info("===============request end===============");

        if (StrUtil.isEmpty(token)) {
            throw new DataProcessingException(AppHttpCodeEnum.NEED_LOGIN.toString());
        }
        User user = userService.checkToken(token);
        if (user == null) {
            throw new DataProcessingException(AppHttpCodeEnum.NEED_LOGIN.toString());
        }
        UserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }


}
